/**
 * ProtoActor-Go WASM 服务器端示例 (Bun)
 * 
 * 此示例展示如何在 Bun 服务器环境中使用 ProtoActor-Go WASM 集成
 * 运行方式: bun run src/examples/bun-server-example.ts
 */

import { ActorBridge, ActorEventType, ActorMessage, ActorPID } from '../wasm/actorBridge';
import { WasmEventManagerFactory, WasmEventType } from '../wasm/wasmEvents';
import { resolve } from 'path';
// @ts-ignore - Bun 特有类型
import { file, serve } from 'bun';

// 创建 GlobaThis 类型扩展
declare global {
  interface Window {
    Go: any;
    __TS_BRIDGE__: {
      invokeTS: (funcName: string, argsJson: string) => string;
    };
    _callbackRegistry: Map<number, (result: any) => void>;
    invokeGoFunction: (funcName: string, argsJson: string) => string;
  }
  
  var __TS_BRIDGE__: {
    invokeTS: (funcName: string, argsJson: string) => string;
  };
  var _callbackRegistry: Map<number, (result: any) => void>;
  var invokeGoFunction: (funcName: string, argsJson: string) => string;
  var Go: any;
}

// 创建全局变量，保存 ActorBridge 实例和当前活跃的 Actor
const globalState = {
  actorBridge: null as ActorBridge | null,
  actors: new Map<string, ActorPID>()
};

// 初始化 WASM 和 ActorBridge
async function initWasm() {
  try {
    console.log('正在初始化 WASM...');
    
    // 初始化全局 Go 变量，在 Bun 环境中，我们需要手动加载并执行 wasm_exec.js
    const wasmExecPath = resolve('./public/wasm_exec.js');
    const wasmExecContent = await file(wasmExecPath).text();
    // 在全局作用域中执行 wasm_exec.js 文件
    eval(wasmExecContent);
    
    // 设置 __TS_BRIDGE__ 对象
    globalThis.__TS_BRIDGE__ = {
      invokeTS: function(funcName: string, argsJson: string) {
        console.log(`收到来自 Go 的函数调用: ${funcName}`);
        
        if (funcName === 'handleGreeting') {
          try {
            const args = JSON.parse(argsJson);
            const message = args[0];
            console.log(`收到消息: ${JSON.stringify(message)}`);
            
            // 处理问候消息
            return JSON.stringify({
              response: `服务器回复: 你好，${message.type}!`
            });
          } catch (e) {
            console.error(`处理消息错误: ${e}`);
            return '';
          }
        }
        return '';
      }
    };
    
    // 创建 ActorBridge 实例
    globalState.actorBridge = new ActorBridge();
    
    // 设置事件监听
    setupEventListeners();
    
    // 初始化 WASM 模块
    const wasmPath = resolve('./public/protoactor.wasm');
    await globalState.actorBridge.initialize(`file://${wasmPath}`);
    
    console.log('WASM 初始化成功!');
    
    // 注册消息处理器
    globalState.actorBridge.registerMessageHandler('handleGreeting', (message: ActorMessage) => {
      console.log(`收到问候消息: ${JSON.stringify(message)}`);
      return { response: `服务器回复: ${message.content || 'Hello World'}` };
    });
    
    return true;
  } catch (error) {
    console.error('WASM 初始化失败:', error);
    return false;
  }
}

// 设置事件监听器
function setupEventListeners() {
  if (!globalState.actorBridge) return;
  
  // 监听 Actor 事件
  globalState.actorBridge.addEventListener(ActorEventType.CREATED, (data) => {
    console.log(`[事件] Actor 已创建: ${JSON.stringify(data)}`);
  });
  
  globalState.actorBridge.addEventListener(ActorEventType.STOPPED, (data) => {
    console.log(`[事件] Actor 已停止: ${JSON.stringify(data)}`);
    
    // 从映射中移除停止的 Actor
    if (data && data.pid) {
      for (const [name, pid] of globalState.actors.entries()) {
        if (pid.id === data.pid.id) {
          globalState.actors.delete(name);
          console.log(`已从映射中移除 Actor: ${name}`);
          break;
        }
      }
    }
  });
  
  globalState.actorBridge.addEventListener(ActorEventType.MESSAGE_SENT, (data) => {
    console.log(`[事件] 消息已发送: ${JSON.stringify(data)}`);
  });
  
  globalState.actorBridge.addEventListener(ActorEventType.MESSAGE_RECEIVED, (data) => {
    console.log(`[事件] 消息已接收: ${JSON.stringify(data)}`);
  });
  
  globalState.actorBridge.addEventListener(ActorEventType.ERROR, (data) => {
    console.error(`[事件] 错误: ${JSON.stringify(data)}`);
  });
  
  // 监听 WASM 事件
  const eventManager = WasmEventManagerFactory.getInstance();
  eventManager.addEventListener(WasmEventType.INITIALIZED, () => {
    console.log(`[WASM 事件] WASM 已初始化`);
  });
  
  eventManager.addEventListener(WasmEventType.ERROR, (data) => {
    console.error(`[WASM 事件] 错误: ${JSON.stringify(data)}`);
  });
}

// 创建 Actor
async function createActor(name: string): Promise<ActorPID | null> {
  if (!globalState.actorBridge) {
    console.error('ActorBridge 未初始化');
    return null;
  }
  
  try {
    // 检查是否已存在同名 Actor
    if (globalState.actors.has(name)) {
      return globalState.actors.get(name) || null;
    }
    
    // 创建新 Actor
    const pid = await globalState.actorBridge.createActor(name);
    console.log(`创建 Actor 成功: ${name}`, pid);
    
    // 保存到映射中
    globalState.actors.set(name, pid);
    
    return pid;
  } catch (error) {
    console.error(`创建 Actor 失败: ${error}`);
    return null;
  }
}

// 发送消息到 Actor
async function sendMessage(actorName: string, message: ActorMessage): Promise<any> {
  if (!globalState.actorBridge) {
    console.error('ActorBridge 未初始化');
    return { error: 'ActorBridge 未初始化' };
  }
  
  try {
    // 获取 Actor PID
    let pid = globalState.actors.get(actorName);
    
    // 如果 Actor 不存在，则创建
    if (!pid) {
      const newPid = await createActor(actorName);
      if (!newPid) {
        return { error: `无法创建 Actor: ${actorName}` };
      }
      pid = newPid;
    }
    
    // 发送消息
    const response = await globalState.actorBridge.sendMessage(pid, message);
    console.log(`发送消息成功:`, response);
    
    return { success: true, response };
  } catch (error) {
    console.error(`发送消息失败: ${error}`);
    return { error: `发送消息失败: ${error}` };
  }
}

// 停止 Actor
async function stopActor(actorName: string): Promise<any> {
  if (!globalState.actorBridge) {
    console.error('ActorBridge 未初始化');
    return { error: 'ActorBridge 未初始化' };
  }
  
  try {
    // 获取 Actor PID
    const pid = globalState.actors.get(actorName);
    
    if (!pid) {
      return { error: `Actor 不存在: ${actorName}` };
    }
    
    // 停止 Actor
    const result = await globalState.actorBridge.stopActor(pid);
    console.log(`停止 Actor 成功: ${actorName}`, result);
    
    // 从映射中移除
    globalState.actors.delete(actorName);
    
    return { success: true, result };
  } catch (error) {
    console.error(`停止 Actor 失败: ${error}`);
    return { error: `停止 Actor 失败: ${error}` };
  }
}

// 启动 HTTP 服务器
async function startServer() {
  console.log('启动 ProtoActor WASM 服务器...');
  
  // 初始化 WASM
  const initResult = await initWasm();
  if (!initResult) {
    console.error('WASM 初始化失败，服务器无法启动');
    // 为 Bun 环境修改退出代码
    Bun.exit(1);
  }
  
  // 创建 HTTP 服务器
  const server = serve({
    port: 3000,
    // 明确类型
    async fetch(req: Request) {
      const url = new URL(req.url);
      
      // 提供静态文件
      if (url.pathname === '/' || url.pathname === '/index.html') {
        return new Response(file('./public/index.html'));
      } else if (url.pathname === '/wasm_exec.js') {
        return new Response(file('./public/wasm_exec.js'));
      } else if (url.pathname === '/protoactor.wasm') {
        return new Response(file('./public/protoactor.wasm'));
      }
      
      // API 端点
      if (url.pathname.startsWith('/api/')) {
        const apiPath = url.pathname.substring(5);
        
        if (req.method === 'POST') {
          try {
            const body = await req.json();
            
            // 创建 Actor
            if (apiPath === 'create-actor') {
              const { name } = body;
              if (!name) {
                return Response.json({ error: '缺少 Actor 名称' }, { status: 400 });
              }
              
              const pid = await createActor(name);
              return Response.json({ success: true, pid });
            }
            
            // 发送消息
            else if (apiPath === 'send-message') {
              const { actorName, message } = body;
              if (!actorName || !message) {
                return Response.json({ error: '缺少 Actor 名称或消息' }, { status: 400 });
              }
              
              const result = await sendMessage(actorName, message);
              return Response.json(result);
            }
            
            // 停止 Actor
            else if (apiPath === 'stop-actor') {
              const { actorName } = body;
              if (!actorName) {
                return Response.json({ error: '缺少 Actor 名称' }, { status: 400 });
              }
              
              const result = await stopActor(actorName);
              return Response.json(result);
            }
            
            // 获取所有 Actor
            else if (apiPath === 'list-actors') {
              const actors = Array.from(globalState.actors.entries()).map(([name, pid]) => ({
                name,
                pid
              }));
              
              return Response.json({ actors });
            }
          } catch (error) {
            console.error('处理 API 请求错误:', error);
            return Response.json({ error: `服务器错误: ${error}` }, { status: 500 });
          }
        }
        
        return Response.json({ error: '不支持的方法' }, { status: 405 });
      }
      
      return new Response('Not Found', { status: 404 });
    }
  });
  
  console.log(`服务器已启动: http://localhost:${server.port}`);
  console.log('可用的 API 端点:');
  console.log('  POST /api/create-actor - 创建 Actor');
  console.log('  POST /api/send-message - 发送消息');
  console.log('  POST /api/stop-actor - 停止 Actor');
  console.log('  POST /api/list-actors - 列出所有 Actor');
}

// 启动服务器
startServer().catch(console.error); 